package com.jasonjan.jiance.module.me;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jasonjan.jiance.R;
import com.jasonjan.jiance.api.ILoginApi;
import com.jasonjan.jiance.bean.LogoutBean;
import com.jasonjan.jiance.global.Constant;
import com.jasonjan.jiance.global.ErrorAction;
import com.jasonjan.jiance.global.RetrofitFactory;
import com.jasonjan.jiance.util.DataCleanManager;
import com.jasonjan.jiance.util.MD5Util;
import com.jasonjan.jiance.util.T;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by JasonJan on 2017/12/1.
 */

public class MeTabLayout extends Fragment {
    private static MeTabLayout instance = null;

    private TextView loginMe;
    private TextView modifyMe;
    private TextView cacheMe;
    private TextView updateMe;
    private TextView logoutMe;


    public static MeTabLayout getInstance() {
        if (instance == null) {
            instance = new MeTabLayout();
        }
        return instance;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_media_tab, container, false);
        initView(view);
        initData();

        return view;
    }

    @Override
    public void onHiddenChanged(boolean hide){
        if(!hide) {
            SharedPreferences checkMe = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
            boolean isLogin = checkMe.getBoolean("isLogin", false);
            if (isLogin) {
                loginMe.setVisibility(View.GONE);
                modifyMe.setVisibility(View.VISIBLE);
                logoutMe.setVisibility(View.VISIBLE);
            } else {
                loginMe.setVisibility(View.VISIBLE);
                modifyMe.setVisibility(View.GONE);
                logoutMe.setVisibility(View.GONE);
            }
            String username = checkMe.getString("username", "");
            if (!username.equals("")) getActivity().setTitle("欢迎您，" + username);
        }
    }

    @Override
    public void onResume() {
        SharedPreferences checkMe=getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        boolean isLogin=checkMe.getBoolean("isLogin",false);
        if(isLogin){
            loginMe.setVisibility(View.GONE);
            modifyMe.setVisibility(View.VISIBLE);
            logoutMe.setVisibility(View.VISIBLE);
        }else{
            loginMe.setVisibility(View.VISIBLE);
            modifyMe.setVisibility(View.GONE);
            logoutMe.setVisibility(View.GONE);
        }
        String username=checkMe.getString("username","");
        if(!username.equals("")) getActivity().setTitle("欢迎您，"+username);
        super.onResume();

    }

    private void initView(View view) {
        loginMe=view.findViewById(R.id.loginMe);
        modifyMe=view.findViewById(R.id.modifyMe);
        cacheMe=view.findViewById(R.id.cacheMe);
        updateMe=view.findViewById(R.id.updateMe);
        logoutMe=view.findViewById(R.id.logoutMe);

        SharedPreferences checkMe=getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        boolean isLogin=checkMe.getBoolean("isLogin",false);
        if(isLogin){
            loginMe.setVisibility(View.GONE);
            modifyMe.setVisibility(View.VISIBLE);
            logoutMe.setVisibility(View.VISIBLE);
        }else{
            loginMe.setVisibility(View.VISIBLE);
            modifyMe.setVisibility(View.GONE);
            logoutMe.setVisibility(View.GONE);
        }
    }

    private void initData() {
        loginMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginActivity.launch("login");
            }
        });

        logoutMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               new MaterialDialog.Builder(getContext())
                        .title("提示")
                        .content("是否退出登录？")
                        .positiveText("确定")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                LoginOutRequest();
                            }
                        })
                        .negativeText("取消")
                        .show();
            }
        });

        cacheMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MaterialDialog.Builder(getContext())
                        .title("提示")
                        .content("是否清除缓存？")
                        .positiveText("确定")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                DataCleanManager.clearAllCache(getContext());
                                T.showShort("已清除缓存！");
                            }
                        })
                        .negativeText("取消")
                        .show();
            }
        });

        updateMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final MaterialDialog.Builder builder=new MaterialDialog.Builder(getContext());
                builder.title("检查更新");
                builder.content("正在检查更新...");
                builder.progress(true,100,true);
                final MaterialDialog dialog=builder.build();
                dialog.show();

                Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        T.showShort("当前版本已经是最新版！");
                    }
                },1236);

            }
        });

        modifyMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyActivity.launch("modify");
            }
        });

    }

    public void LoginOutRequest(){

        //构造请求参数
        JSONObject requestJson=new JSONObject();
        try{
            SharedPreferences user_info=getContext().getSharedPreferences("user_info",Context.MODE_PRIVATE);
            String token=user_info.getString("token","");
            requestJson.put("sign", MD5Util.md5(Constant.salt+token));
        }catch (JSONException e){
            e.printStackTrace();
        }
        RequestBody body= RequestBody.create(MediaType.parse(Constant.Content_Type),requestJson.toString());
        RetrofitFactory.getRetrofit().create(ILoginApi.class).getLogout(body)
                .subscribeOn(Schedulers.io())
                .switchMap(new Function<LogoutBean, Observable<LogoutBean>>() {
                    @Override
                    public Observable<LogoutBean> apply(@NonNull LogoutBean logoutBean) throws Exception {

                        LogoutBean data = logoutBean;
                        Log.d("login","data获取数据为："+data.toString());
                        return Observable.just(data);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<LogoutBean>() {
                    @Override
                    public void accept(@NonNull LogoutBean logoutBean) throws Exception {

                            T.showShort("已退出登录！");
                            SharedPreferences user_info=getContext().getSharedPreferences("user_info",Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor=user_info.edit();
                            editor.clear();
                            editor.commit();
                            SharedPreferences checkMe=getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
                            boolean isLogin=checkMe.getBoolean("isLogin",false);
                            if(isLogin){
                                loginMe.setVisibility(View.GONE);
                                modifyMe.setVisibility(View.VISIBLE);
                                logoutMe.setVisibility(View.VISIBLE);
                            }else{
                                loginMe.setVisibility(View.VISIBLE);
                                modifyMe.setVisibility(View.GONE);
                                logoutMe.setVisibility(View.GONE);
                            }
                            getActivity().setTitle("我");

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        T.showShort("退出登录失败！");
                        ErrorAction.print(throwable);
                    }
                });
    }

    @Override
    public void onDestroy() {
        if (instance != null) {
            instance = null;
        }
        super.onDestroy();
    }
}
